/**
 * 模板编辑器组件
 * 提供模板创建和编辑功能
 */

import React, { useState, useEffect } from 'react'
import {
  Modal,
  Form,
  Input,
  Select,
  Switch,
  Button,
  Row,
  Col,
  Card,
  Tag,
  Space,
  message,
  Typography,
  Divider
} from 'antd'
import {
  SaveOutlined,
  EyeOutlined,
  InfoCircleOutlined
} from '@ant-design/icons'
import {
  DocumentTemplate,
  CreateTemplateInput,
  UpdateTemplateInput,
  TemplateCategory,
  TemplateLabelType
} from '../../../types/template'
import { ContentType } from '../../../types/document'
import { templateService } from '../../../services/templates'
import { getTemplateCategoryInfo, getTemplateTypeInfo } from '../../../services/templates/builtInTemplates'

const { TextArea } = Input
const { Option } = Select
const { Text, Paragraph } = Typography

interface TemplateEditorProps {
  visible: boolean
  template?: DocumentTemplate | null
  isCreate?: boolean
  onSave: () => void
  onCancel: () => void
}

/**
 * 模板编辑器主组件
 */
export const TemplateEditor: React.FC<TemplateEditorProps> = ({
  visible,
  template,
  isCreate = false,
  onSave,
  onCancel
}) => {
  const [form] = Form.useForm()
  const [loading, setLoading] = useState(false)
  const [previewVisible, setPreviewVisible] = useState(false)
  const [previewContent, setPreviewContent] = useState('')

  const categoryInfos = getTemplateCategoryInfo()
  const typeInfos = getTemplateTypeInfo()

  // 初始化表单
  useEffect(() => {
    if (visible) {
      if (template && !isCreate) {
        // 编辑模式：填充现有模板数据
        form.setFieldsValue({
          name: template.name,
          description: template.description,
          category: template.category,
          type: template.type,
          contentType: template.contentType,
          content: template.content,
          author: template.metadata.author,
          difficulty: template.metadata.difficulty,
          language: template.metadata.language,
          license: template.metadata.license,
          tags: template.tags.join(', ')
        })
      } else {
        // 创建模式：重置表单
        form.resetFields()
        form.setFieldsValue({
          contentType: ContentType.TEXT_DOCUMENT,
          difficulty: 'medium',
          language: 'zh-CN',
          author: '用户'
        })
      }
    }
  }, [visible, template, isCreate, form])

  // 处理保存
  const handleSave = async () => {
    try {
      const values = await form.validateFields()
      setLoading(true)

      const tags = values.tags ? values.tags.split(',').map((tag: string) => tag.trim()).filter(Boolean) : []
      const estimatedLength = values.content ? values.content.replace(/\s/g, '').length : 0

      if (isCreate) {
        // 创建新模板
        const input: CreateTemplateInput = {
          name: values.name,
          description: values.description,
          category: values.category,
          type: values.type,
          contentType: values.contentType,
          content: values.content,
          metadata: {
            author: values.author || '用户',
            difficulty: values.difficulty,
            language: values.language,
            license: values.license,
            estimatedLength
          },
          tags
        }

        const result = await templateService.createTemplate(input)
        if (result.success) {
          message.success('模板创建成功')
          onSave()
        } else {
          message.error(`创建失败: ${result.error}`)
        }
      } else if (template) {
        // 更新现有模板
        const input: UpdateTemplateInput = {
          name: values.name,
          description: values.description,
          category: values.category,
          type: values.type,
          content: values.content,
          metadata: {
            ...template.metadata,
            author: values.author,
            difficulty: values.difficulty,
            language: values.language,
            license: values.license,
            estimatedLength
          },
          tags
        }

        const result = await templateService.updateTemplate(template.id, input)
        if (result.success) {
          message.success('模板更新成功')
          onSave()
        } else {
          message.error(`更新失败: ${result.error}`)
        }
      }
    } catch (error) {
      console.error('[模板编辑器] 保存失败:', error)
      message.error('保存失败')
    } finally {
      setLoading(false)
    }
  }

  // 处理预览
  const handlePreview = async () => {
    try {
      const values = await form.validateFields(['content'])
      setPreviewContent(values.content || '')
      setPreviewVisible(true)
    } catch (error) {
      message.warning('请先填写模板内容')
    }
  }

  // 处理取消
  const handleCancel = () => {
    form.resetFields()
    onCancel()
  }

  return (
    <>
      <Modal
        title={isCreate ? '创建模板' : '编辑模板'}
        visible={visible}
        onCancel={handleCancel}
        width={900}
        style={{ top: 20 }}
        footer={[
          <Button key="cancel" onClick={handleCancel}>
            取消
          </Button>,
          <Button key="preview" icon={<EyeOutlined />} onClick={handlePreview}>
            预览
          </Button>,
          <Button
            key="save"
            type="primary"
            icon={<SaveOutlined />}
            loading={loading}
            onClick={handleSave}
          >
            {isCreate ? '创建' : '保存'}
          </Button>
        ]}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            contentType: ContentType.TEXT_DOCUMENT,
            difficulty: 'medium',
            language: 'zh-CN',
            author: '用户'
          }}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="模板名称"
                rules={[
                  { required: true, message: '请输入模板名称' },
                  { max: 100, message: '模板名称不能超过100个字符' }
                ]}
              >
                <Input placeholder="请输入模板名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="contentType"
                label="内容类型"
                rules={[{ required: true, message: '请选择内容类型' }]}
              >
                <Select placeholder="选择内容类型">
                  <Option value={ContentType.TEXT_DOCUMENT}>文本文档</Option>
                  <Option value={ContentType.STORYBOARD} disabled>分镜脚本（暂不支持）</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="description"
            label="模板描述"
            rules={[
              { max: 500, message: '描述不能超过500个字符' }
            ]}
          >
            <TextArea
              placeholder="请简要描述模板的用途和特点"
              rows={2}
              showCount
              maxLength={500}
            />
          </Form.Item>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="category"
                label="模板分类"
                rules={[{ required: true, message: '请选择模板分类' }]}
              >
                <Select placeholder="选择分类">
                  {categoryInfos.map(info => (
                    <Option key={info.category} value={info.category}>
                      <span style={{ marginRight: 8 }}>{info.icon}</span>
                      {info.name}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="type"
                label="模板类型"
                rules={[{ required: true, message: '请选择模板类型' }]}
              >
                <Select placeholder="选择类型">
                  {typeInfos.map(info => (
                    <Option key={info.type} value={info.type}>
                      <Tag color={info.color} style={{ margin: 0 }}>
                        {info.name}
                      </Tag>
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="difficulty"
                label="难度级别"
                rules={[{ required: true, message: '请选择难度级别' }]}
              >
                <Select placeholder="选择难度">
                  <Option value="easy">
                    <Tag color="green">简单</Tag>
                  </Option>
                  <Option value="medium">
                    <Tag color="orange">中等</Tag>
                  </Option>
                  <Option value="hard">
                    <Tag color="red">困难</Tag>
                  </Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="content"
            label={
              <Space>
                <span>模板内容</span>
                <Text type="secondary" style={{ fontSize: 12 }}>
                  <InfoCircleOutlined /> 使用 {'{变量名}'} 格式定义变量，例如：{'{标题}'}、{'{内容}'}
                </Text>
              </Space>
            }
            rules={[
              { required: true, message: '请输入模板内容' },
              { max: 50000, message: '内容不能超过50000个字符' }
            ]}
          >
            <TextArea
              placeholder="请输入模板内容，可以使用 {变量名} 格式定义可替换的部分"
              rows={12}
              showCount
              maxLength={50000}
            />
          </Form.Item>

          <Divider orientation="left" style={{ fontSize: 14 }}>
            元数据
          </Divider>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="author"
                label="作者"
              >
                <Input placeholder="模板作者" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="language"
                label="语言"
              >
                <Select>
                  <Option value="zh-CN">简体中文</Option>
                  <Option value="en-US">English</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="license"
                label="许可证"
              >
                <Input placeholder="如：MIT、CC BY 4.0" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="tags"
            label="标签"
            extra="多个标签用逗号分隔，最多10个标签"
          >
            <Input placeholder="例如：新闻,报道,正式,模板" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 内容预览对话框 */}
      <Modal
        title="模板内容预览"
        visible={previewVisible}
        onCancel={() => setPreviewVisible(false)}
        footer={[
          <Button key="close" onClick={() => setPreviewVisible(false)}>
            关闭
          </Button>
        ]}
        width={800}
        style={{ top: 20 }}
      >
        <div
          style={{
            padding: 16,
            backgroundColor: '#f5f5f5',
            borderRadius: 6,
            maxHeight: 500,
            overflow: 'auto',
            fontFamily: 'monospace',
            fontSize: 13,
            lineHeight: 1.6,
            whiteSpace: 'pre-wrap'
          }}
        >
          {previewContent || '暂无内容'}
        </div>
      </Modal>
    </>
  )
}